package cn.xiuxius.askbox.controller.user;


import cn.xiuxius.askbox.common.constant.AccountState;
import cn.xiuxius.askbox.common.context.AppContext;
import cn.xiuxius.askbox.pojo.dto.common.LoginDTO;
import cn.xiuxius.askbox.pojo.dto.common.RegisterDTO;
import cn.xiuxius.askbox.pojo.dto.query.UserQueryDTO;
import cn.xiuxius.askbox.pojo.dto.update.UserUpdateDTO;
import cn.xiuxius.askbox.pojo.result.Result;
import cn.xiuxius.askbox.pojo.vo.LoginVO;
import cn.xiuxius.askbox.pojo.vo.UserVO;
import cn.xiuxius.askbox.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoxiu
 * @since 2024-07-20
 */
@Api(tags = "用户-用户接口")
@RestController("userUserController")
@RequestMapping("/user/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO dto) {
        LoginVO vo = userService.login(dto);
        return Result.success(vo);
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDTO dto) {
        userService.register(dto);
        return Result.success();
    }

    @ApiOperation("获取用户主页信息")
    @GetMapping("/home")
    public Result getUserHome() {
        UserQueryDTO dto = new UserQueryDTO();
        dto.setUuid(AppContext.getUserUuid());
        UserVO vo = userService.getUserByUuid(dto);
        vo.setRegisterIp(null);
        vo.setLastLoginIp(null);
        vo.setUpdateTime(null);
        return Result.success(vo);
    }

    @ApiOperation("修改用户信息")
    @PutMapping("/home")
    public Result updateUser(@RequestBody UserUpdateDTO dto) {
        dto.setUuid(AppContext.getUserUuid());
        userService.updateUser(dto);
        return Result.success();
    }

    @ApiOperation("根据用户名查询用户")
    @GetMapping("/home/{username}")
    public Result getUserByUsername(@PathVariable String username) {
        UserQueryDTO dto = new UserQueryDTO();
        dto.setUsername(username);
        dto.setState(AccountState.ALIVE);
        UserVO vo = userService.getUserByUsername(dto);
        //脱敏
        vo.setPhone(null);
        vo.setEmail(null);
        vo.setCreateTime(null);
        vo.setUpdateTime(null);
        vo.setRegisterIp(null);
        vo.setLastLoginIp(null);
        vo.setState(null);
        return Result.success(vo);
    }

}
